package com.tyk.bookstore.back.system.valid.validator;

import com.tyk.bookstore.back.common.core.valid.util.ValidUtil;
import com.tyk.bookstore.back.system.valid.annotation.MenuFieldValid;
import com.tyk.bookstore.back.system.valid.constant.MenuFieldValidConstant;
import com.tyk.bookstore.back.system.valid.type.MenuFieldValidType;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;

import java.util.Arrays;

public class MenuFieldConstraintValidator implements ConstraintValidator<MenuFieldValid, Object> {
    private MenuFieldValidType[] types;

    @Override
    public void initialize(MenuFieldValid constraintAnnotation) {
        types = constraintAnnotation.value();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        if(value == null) {
            return true;
        }

        for (MenuFieldValidType type : types) {
            switch (type) {
                case NAME_LIKE -> {
                    if(value instanceof String) {
                        return ValidUtil.validString((String)value, MenuFieldValidConstant.NAME_LIKE_MIN_LENGTH, MenuFieldValidConstant.NAME_LIKE_MAX_LENGTH ,MenuFieldValidConstant.NAME_LIKE_PATTERN);
                    }
                }
                case NAME -> {
                    if(value instanceof String) {
                        return ValidUtil.validString((String)value, MenuFieldValidConstant.NAME_MIN_LENGTH, MenuFieldValidConstant.NAME_MAX_LENGTH ,MenuFieldValidConstant.NAME_PATTERN);
                    }
                }
                case PATH,REDIRECT,COMPONENT -> {
                    if(value instanceof String) {
                        return ValidUtil.validString((String)value, MenuFieldValidConstant.PATH_MIN_LENGTH, MenuFieldValidConstant.PATH_MAX_LENGTH, MenuFieldValidConstant.PATH_PATTERN);
                    }
                }
                case TITLE -> {
                    if (value instanceof String) {
                        return ValidUtil.validString((String) value, MenuFieldValidConstant.TITLE_MIN_LENGTH, MenuFieldValidConstant.TITLE_MAX_LENGTH, MenuFieldValidConstant.TITLE_PATTERN);
                    }
                }
                case TITLE_LIKE -> {
                    if (value instanceof String) {
                        return ValidUtil.validString((String) value, MenuFieldValidConstant.TITLE_LIKE_MIN_LENGTH, MenuFieldValidConstant.TITLE_LIKE_MAX_LENGTH, MenuFieldValidConstant.TITLE_LIKE_PATTERN);
                    }
                }
                case ICON -> {
                    if(value instanceof String) {
                        return ValidUtil.validString((String) value, MenuFieldValidConstant.ICON_MIN_LENGTH, MenuFieldValidConstant.ICON_MAX_LENGTH, MenuFieldValidConstant.ICON_PATTERN);
                    }
                }
            }
        }
        throw new IllegalArgumentException("非法取值" + Arrays.toString(types) + value);
    }
}
